package com.googlecode.imanager.client.form;

import com.googlecode.imanager.client.Container;
import com.googlecode.imanager.client.bridge.form.ITextBox;
import com.googlecode.imanager.client.event.KeyEvent;
import com.googlecode.imanager.client.util.Utils;
import com.googlecode.imanager.client.value.mask.InputMask;

/**
 * @author wellsantos@wellsantos.com
 * @since 0.01
 */
public class TextBox extends InputText implements ITextBox {

    private static final long serialVersionUID = 1L;

    private InputMask mask;
    
    public TextBox() {
    }

    public TextBox(Container parent) {
        this();
        setParent(parent);
    }

    @Override
    protected String onChanging(String text) {
        if (mask != null){
            return mask.maskText(text);
        }
        return text;
    }

    @Override
    protected void handleDefault(KeyEvent e) {
        if (mask != null
                && !e.isPreventDefault()
                && e.getTarget() == this){
            mask.maskKeyEvent(this, e);
        }
        super.handleDefault(e);
    }

    @Override
    public boolean hasInput() {
        if (mask != null){
            return !getText().equals(mask.getDefaultText());
        }
        return super.hasInput();
    }

    public InputMask getMask() {
        return mask;
    }

    public void setMask(InputMask mask) {
        if (!Utils.isEquals(this.mask, mask)){
            this.mask = mask;
            changeText(getText());
        }
    }

    @Override
    public TextBox clone() {
        return (TextBox) super.clone();
    }

    @Override
    protected ITextBox getBridge() {
        return (ITextBox) lookupBridge();
    }

}
